package wifiunion.com.notice.widget.selectmemberdialog;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.CommonUtils;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.MyNoticeListener;
import wifiunion.com.notice.R;
import wifiunion.com.notice.entity.NotificationRequest;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.widget.selectmemberdialog.adapter.SelectMemberListViewAdapter;
import wifiunion.com.notice.widget.selectmemberdialog.adapter.SelectMemberTreeAdapter;
import wifiunion.com.notice.widget.selectmemberdialog.entity.Node;
import wifiunion.com.notice.widget.selectmemberdialog.entity.SelectMember;
import wifiunion.com.notice.widget.selectmemberdialog.presenter.SelectMemberPresenter;
import wifiunion.com.notice.widget.selectmemberdialog.utils.SelectMemberTreeHelper;

/**
 * 选择用户对话框
 */
public class SelectMemberDialog extends DialogFragment implements View.OnClickListener, SelectMemberContact.SelectMemberView {

    private View mMainView;
    private TextView titleTxt, cancelTxt, confirmTxt;
    private ListView listview;
    private EditText searchEdt;
    private Button searchBtn;
    private String authtoken;
    private String currentPid;


    /**
     * 请求页面类型
     * 0 通知模块  1巡查模块  2 曝光模块
     * 3 通知模块 添加通知对象
     */
    private int mRequestPageType;


    /**
     * 功能模块类型，
     * 0曝光频次，1签到管理
     * 2考勤管理，3访客管理
     * 4实时计数 -2 通知
     */
    private int moduleType = -1;
    /**
     * 通知的uuid
     */
    private String noticeUuid = "0";

    /**
     * 4 新增修改通知对象
     */
    private String targetType;

    private SelectMemberPresenter selectMemberPresenter;

    private ArrayList<SelectMember> datalist = new ArrayList<>();

    /**
     * 所有的节点
     */
    private List<Node> allNodes = new ArrayList<>();

    private SelectMemberTreeAdapter selectMemberTreeAdapter;

    private ProgressBar loadPb;

    private int hasTemp = 0;

    private String minTemp,maxTemp;

    /**
     * 回调接口
     */
    private MyNoticeListener myNoticeListener;

    public static SelectMemberDialog newInstance(String noticeuuid, int moduletype, int type) {
        Bundle args = new Bundle();
        SelectMemberDialog fragment = new SelectMemberDialog();
        args.putString("noticeuuid", noticeuuid);
        args.putInt("moduletype", moduletype);
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 4通知对象 对话框
     *
     * @param noticeuuid
     * @param moduletype
     * @param type
     * @param targetType
     * @return
     */
    public static SelectMemberDialog newInstance(String noticeuuid, int moduletype, int type, String targetType) {
        Bundle args = new Bundle();
        SelectMemberDialog fragment = new SelectMemberDialog();
        args.putString("noticeuuid", noticeuuid);
        args.putInt("moduletype", moduletype);
        args.putInt("type", type);
        args.putString("targetType", targetType);
        fragment.setArguments(args);
        return fragment;
    }

    public void setCallback(MyNoticeListener myNoticeListener) {
        this.myNoticeListener = myNoticeListener;
    }

    public void setTempParam(String min,String max){
        hasTemp = 1;
        minTemp = min;
        maxTemp = max;
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        Bundle bundle = getArguments();
        noticeUuid = bundle.getString("noticeuuid");
        moduleType = bundle.getInt("moduletype");
        mRequestPageType = bundle.getInt("type");
        targetType = bundle.getString("targetType");
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        selectMemberPresenter = new SelectMemberPresenter(0, "100", mRequestPageType, this);
        selectMemberPresenter.onAttach(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        selectMemberPresenter.onDetach();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        mMainView = inflater.inflate(R.layout.dialog_selectmember, container);
        initview();
        return mMainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        try {
            selectMemberTreeAdapter = new SelectMemberTreeAdapter(listview, getContext(), allNodes/*, visNodes*/);
            listview.setAdapter(selectMemberTreeAdapter);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        getGroupdata();
    }

    @Override
    public void onStart() {
        super.onStart();
        WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = getContext().getResources().getDimensionPixelSize(
                R.dimen.dp_600);
        lp.height = (int) (CommonUtils.getScreenHeight(getContext()) * 0.9f);
        getDialog().getWindow().setAttributes(lp);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.cancel_txt) {
            dismiss();
        } else if (v.getId() == R.id.confirm_txt) {
            addMembersRequest();
        } else if (v.getId() == R.id.search_btn) {
            getGroupdata();
        }
    }

    private void initview() {
        titleTxt = (TextView) mMainView.findViewById(R.id.title_txt);
        if (TextUtils.isEmpty(targetType)) {
            titleTxt.setText("添加识别对象");
        } else {
            titleTxt.setText("添加通知对象");
        }
        loadPb = (ProgressBar) mMainView.findViewById(R.id.loading_pb);
        cancelTxt = (TextView) mMainView.findViewById(R.id.cancel_txt);
        confirmTxt = (TextView) mMainView.findViewById(R.id.confirm_txt);
        listview = (ListView) mMainView.findViewById(R.id.dialog_tree_listview);
        searchEdt = (EditText) mMainView.findViewById(R.id.search_edt);
        searchBtn = (Button) mMainView.findViewById(R.id.search_btn);
        cancelTxt.setOnClickListener(this);
        confirmTxt.setOnClickListener(this);
        searchBtn.setOnClickListener(this);
    }


    private void getGroupdata() {
        showProgress();
        try {
            selectMemberPresenter = new SelectMemberPresenter(0, "100", mRequestPageType, this);
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("Authorization", authtoken);
            if (!TextUtils.isEmpty(searchEdt.getText().toString())) {
                params.put("condition", searchEdt.getText().toString());
            }
            params.put("uuid", noticeUuid);

            if (mRequestPageType == 3) {
                params.put("targetType", targetType);//4通知对象分组类型
            }
            selectMemberPresenter.start(params);
        } catch (Exception e) {
            e.printStackTrace();
            dismissProgress();
        }
    }

    private void getMemberdata(String groupUuid) {

        showProgress();
        try {
            selectMemberPresenter = new SelectMemberPresenter(1, groupUuid, mRequestPageType, this);
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("Authorization", authtoken);
            if (!TextUtils.isEmpty(searchEdt.getText().toString())) {
                params.put("condition", searchEdt.getText().toString());
            }
            params.put("uuid", noticeUuid);
            params.put("pageNum", 1);
            params.put("pageSize", 5000);
            params.put("groupUuid", groupUuid);


            if (mRequestPageType == 3) {
                params.put("targetType", targetType);//4通知对象分组类型
            }
            selectMemberPresenter.start(params);
        } catch (Exception e) {
            e.printStackTrace();
            dismissProgress();
        }
    }

    @Override
    public void setPresenter(BasePresenter tp) {

    }

    @Override
    @NonNull
    public void getGroupSuccess(Object result) {

        dismissProgress();
        ArrayList<SelectMember> list = (ArrayList) result;

        if (list != null && !list.isEmpty()) {
            datalist.clear();
            datalist.addAll(list);
            SelectMember topRegisterMember = new SelectMember(0, "100", "已登记人员", "1000", 0);
            SelectMember topUnRegisterMember = new SelectMember(0, "200", "未登记人员", "2000", 0);
            SelectMember subUnRegisterMember = new SelectMember(0, "0", "全部", "200", 0);

            if (!TextUtils.isEmpty(targetType)) { // 管理员 需要添加一个全部
                SelectMember subRegisterMember = new SelectMember(0, "-1", "全部", "100", 0);
                datalist.add(topRegisterMember);
                datalist.add(0,subRegisterMember);//'全部'放在前面
                datalist.add(topUnRegisterMember);
                datalist.add(subUnRegisterMember);
                datalist.remove(0);
            } else {
                datalist.remove(datalist.size() - 1);
                datalist.add(topRegisterMember);
                datalist.add(topUnRegisterMember);
                datalist.add(subUnRegisterMember);
            }

            try {
                allNodes.clear();
                allNodes.addAll(SelectMemberTreeHelper.getSortedNodes(datalist, 1));
                selectMemberTreeAdapter.setOnTreeNodeClickListener(new SelectMemberListViewAdapter.OnTreeNodeClickListener() {
                    @Override
                    public void onClick(Node node, int position) {
                        //是否是人员节点，如果是就不做响应，否则判断是否请求过数据，没请求过，就请求
                        if (TextUtils.isEmpty(node.getPhone())) {
                            // 未登记人员的 不做处理
                            if ("0".equals(node.getId())) {
                                return;
                            }
                            if (node.getChildren() == null || node.getChildren().isEmpty()) {
                                currentPid = node.getId();
                                getMemberdata(currentPid);
                            } else {
                                selectMemberTreeAdapter.expandOrCollapse(position);
                            }
                        }

                    }
                });

                selectMemberTreeAdapter.notifyDataSetChanged();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void getGroupFailed(Object error) {
        dismissProgress();
    }

    @Override
    @NonNull
    public void getMemberSuccess(Object result) {

        ArrayList<SelectMember> list = (ArrayList) result;

        if (list != null && !list.isEmpty()) {
            try {
                /**
                 * 保存之前选中状态的选项，否则会覆盖之前选中未提交的对象
                 */
                for (Node node : allNodes) {
                    if (node.getChecked() == 1) {
                        for (SelectMember sm : datalist) {
                            if (node.getId().equals(sm.uuid)) {
                                sm.isSelected = 1;
                            }
                        }
                    }
                }
                datalist.addAll(list);
                List<Node> all = SelectMemberTreeHelper.getSortedNodes(datalist, 2, currentPid);  //
                allNodes.clear();
                allNodes.addAll(all);


            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            selectMemberTreeAdapter.notifyDataSetChanged();

        }
        dismissProgress();

    }

    @Override
    public void getMemberFailed(Object error) {
        dismissProgress();
    }

    @Override
    public void addMemberSuccess(Object result) {

        myNoticeListener.refreshData((String) result);
        Toast.makeText(getContext(), "添加成功", Toast.LENGTH_SHORT).show();
        dismiss();

    }

    @Override
    public void addMemberFailed(Object error) {
        myNoticeListener.refreshCancelData("");
        Toast.makeText(getContext(), "添加失败", Toast.LENGTH_SHORT).show();
        dismiss();
    }

    private void showProgress() {
        loadPb.setVisibility(View.VISIBLE);
    }

    private void dismissProgress() {
        loadPb.setVisibility(View.GONE);
    }


    private void addMembersRequest() {

        HashMap<String, Object> params = new HashMap<>();
        params.put("Authorization", authtoken);
        params.put("uuid", noticeUuid);
        List<NotificationRequest> data = new ArrayList<NotificationRequest>();

        for (Node node : allNodes) {
            NotificationRequest nr = new NotificationRequest();
            if (node.getChecked() == 1) {

                //正常需要的参数是fromuuid,添加通知对象哪里需要的是targetuuid
                if (mRequestPageType != 3) {
                    nr.setFromUuid(node.getId());
                } else {
                    nr.setTargetUuid(node.getId());
                }
                if (!TextUtils.isEmpty(node.getPhone())) {
                    nr.setIsGroup(0);
//                    if (node.getParent().getChecked() != 1 || TextUtils.isEmpty(searchEdt.getText())) {
                    data.add(nr);
//                    }
                } else {
                    //如果是搜索出来的结果，分组被选中，不做提交。
                    if (TextUtils.isEmpty(searchEdt.getText())) {
                        nr.setIsGroup(1);
                        data.add(nr);
                    }
                }
            }
        }
        if (data == null || data.isEmpty()) {
            myNoticeListener.refreshCancelData("");
            dismiss();
            return;
        }
        params.put("data", data);
        if (moduleType == -1 || moduleType == -2) {

        } else {
            params.put("moduleType", moduleType);
        }

        if (mRequestPageType == 3) {
            params.put("targetType", targetType);// 4 通知对象类型
        }


        if(hasTemp==1)
        {
            params.put("isSetTemperature",1);
            params.put("temperatureMin",minTemp);
            params.put("temperatureMax",maxTemp);
        }

        selectMemberPresenter = new SelectMemberPresenter(2, "", mRequestPageType, this);
        selectMemberPresenter.start(params);
    }
}
